package com.lcc.lynx.base.system.service.impl;

import com.lcc.lynx.base.system.constant.LogTypeConst;
import com.lcc.lynx.base.system.constant.SendStateConst;
import com.lcc.lynx.base.system.pojo.dv.SysApiDataDV;
import com.lcc.lynx.base.system.pojo.dv.SysApiLogDV;
import com.lcc.lynx.base.system.pojo.dv.SysUserDV;
import com.lcc.lynx.base.system.service.SysApiDataService;
import com.lcc.lynx.base.system.service.SysApiLogService;
import com.lcc.lynx.base.system.mapper.SysApiLogMapper;
import com.lcc.lynx.common.utils.DateUtil;
import com.lcc.lynx.security.Session;
import com.lcc.lynx.security.log.IApiLogRecord;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 日志管理服务实现
 * @auth lcc
 * @date 2025-02-24
 */
@Service
@Transactional
@AllArgsConstructor
public class SysApiLogServiceImpl implements SysApiLogService, IApiLogRecord {

    private SysApiLogMapper mapper;

    private SysApiDataService sysApiDataService;


    @Override
    public SysApiLogMapper getMapper() {
       return mapper;
    }

    @Override
    public void record(Date startTime, String requestBody, String responseBody, String requestUrl, String headers,
                        String method, String contentType) {
        SysApiLogDV sysApiLogDV = new SysApiLogDV();
        sysApiLogDV.setStartTime(startTime);
        sysApiLogDV.setEndTime(new Date());
        sysApiLogDV.setUrl(requestUrl);
        sysApiLogDV.setLogCode("LYNX");
        sysApiLogDV.setLogType(LogTypeConst.SYS_LOG);
        sysApiLogDV.setSendState(SendStateConst.SUCCESS);
        sysApiLogDV.setSystemCode("LYNX");
        sysApiLogDV.setDatePartition(DateUtil.getDate_yyyyMM());
        SysUserDV sysUserDV = Session.getUser();
        if(sysUserDV != null){
            sysApiLogDV.setUserId(sysUserDV.getUserId());
        }
        sysApiLogDV.setMethod(method);
        sysApiLogDV.setContentType(contentType);
        this.insert(sysApiLogDV);

        SysApiDataDV sysApiDataDV = new SysApiDataDV();
        sysApiDataDV.setLogId(sysApiLogDV.getLogId());
        sysApiDataDV.setRequestBody(requestBody);
        sysApiDataDV.setResponseBody(responseBody);
        sysApiDataDV.setHeaders(headers);
        sysApiDataDV.setDatePartition(sysApiLogDV.getDatePartition());
        sysApiDataService.insert(sysApiDataDV);

    }
}